#include "../tools.h"



void heapify(vector<int>& arr, int n, int i);
void heap_sort(vector<int>& arr);

int main(int argc, char const *argv[])
{
    vector<int> data = {6, 2, 1, 7, 9, 3, 4, 5, 10, 8};

    heap_sort(data);
    show(data);

    return 0;
}

void heapify(vector<int>& arr, int n, int i){
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;
    if(left < n && arr[left] > arr[largest]) largest = left;
    if(right < n && arr[right] > arr[largest]) largest = right;

    if(largest != i) {
        swap(arr[largest], arr[i]);
        heapify(arr, n, largest);
    }
}

void heap_sort(vector<int>& arr){
    int n = arr.size();
    for(int i = n - 1; i >= 0; --i)
        heapify(arr, n, i);

    for(int i = n - 1; i > 0; --i){
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
}
